package com.ruoyi.system.service.impl;


import java.util.HashMap;
import java.util.List;
import java.util.Map;


import javax.servlet.http.HttpServletRequest;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.SysFactoryMapper;
import com.ruoyi.system.mapper.SysRoleFactoryMapper;
import com.ruoyi.system.mapper.SysUserFactoryMapper;
import com.ruoyi.system.domain.SysFactory;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.service.ISysFactoryService;
import lombok.extern.slf4j.Slf4j;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.redis.util.RedisUtils;
import com.ruoyi.common.utils.ServletUtils;

/**
 * 基地Service业务层处理
 * 
 * @author ygx
 * @date 2020-06-13
 */
@Service
@Slf4j
public class SysFactoryServiceImpl implements ISysFactoryService 
{
	@Autowired
	private RedisUtils         redis;
		
	@Autowired
    private SysFactoryMapper sysFactoryMapper; 
	@Autowired 
	private SysUserFactoryMapper sysUserFactoryMapper;
	@Autowired
	private SysRoleFactoryMapper sysRoleFactoryMapper;

    /**
     * 查询基地
     * 
     * @param factoryId 基地ID
     * @return 基地
     */
    @Override
    public SysFactory selectSysFactoryById(Long factoryId)
    {
        return sysFactoryMapper.selectSysFactoryById(factoryId);
    }

    /**
     * 查询基地列表
     * 
     * @param sysFactory 基地
     * @return 基地
     */
    @Override
    public List<SysFactory> selectSysFactoryList(SysFactory sysFactory)
    {
        return sysFactoryMapper.selectSysFactoryList(sysFactory);
    }
    
    /**
     * 查询所有生产基地
     * 
     * @return 生产基地列表
     */
    @Override
    public List<SysFactory> selectFactoryAll()
    {
        return selectSysFactoryList(new SysFactory());
    }
    
	   /**
         * 根据角色编号查询基地编号（用于勾选）
         * @param roleId
         * @return
         * @author zmr
       */
    public List<SysFactory> selectFactoryIdsByRoleId(Long roleId)
    {
    	return sysFactoryMapper.selectFactoryIdsByRoleId(roleId);
    };
    
	/**
     * 根据用户id查询基地信息、erp采购部门信息及货币信息
     * @param factory_id,f.factory_code,f.factory_name,erpdept_code,erpdept_name,currency_type
     * @return
     * @author ygx
    */
    public List<SysFactory> selectSysFactoryByUserId(Long userId)
    {
    	return sysFactoryMapper.selectSysFactoryByUserId(userId);
    };
    
    /**
    * 根据基地code、name、id查询erp部门及币种
    * @param factory code、name、id
    * @return erpdept_code,erpdept_name,currency_type
    * @author ygx
    */
  public List<SysFactory> selectErpdeptByfactory(SysFactory sysFactory)
   {
	  return sysFactoryMapper.selectErpdeptByfactory(sysFactory);
   };

   /**
    * 根据基地userid查询erp采购部门及币种
    * @param USERid
    * @return erpdept_code,erpdept_name,currency_type
    * @author ygx
   */
   public List<SysFactory> selectErpdeptByUserId()
   {   
	   HttpServletRequest request = ServletUtils.getRequest(); 
	   Long userId = Long.valueOf(request.getHeader(Constants.CURRENT_ID));
	   return sysFactoryMapper.selectErpdeptByUserId(userId);
   };

    
    /**
     *  根据用户查询基地列表
     * 
     * @param userid 用户id
     * @return 基地集合
     */
    @Override
    public List<SysFactory> selectSysFactoryListByUserid(Long userId)
    {
        return sysFactoryMapper.selectFactorysByUserId(userId);
    }
    
    /**
     *  将用户与基地对应关系写入redis
     * 
     * @param userid 用户id
     * @return 基地集合
     */
    @Override
    public String insertRedis(String factoryCode)
    { 
    if (factoryCode != null) {
       HttpServletRequest request = ServletUtils.getRequest() ;
       String token = request.getHeader("token");
       SysUser currentUser = redis.get(Constants.ACCESS_TOKEN + token, SysUser.class);
       if (currentUser != null)
       {   Map<String, String> mmap = new HashMap<String, String>();
           Long user = currentUser.getUserId();
            mmap.put("factoryCode", factoryCode);
            mmap.put("sysToken", token);
    	   redis.set(Constants.ACCESS_FACTORY + ":" + token + "_" + currentUser.getUserId(),mmap);
    	   SysFactory factoryRedis = redis.get(Constants.ACCESS_FACTORY + ":" + token + "_" + currentUser.getUserId(),SysFactory.class);
    	   String factoryCodeRedis = factoryRedis.getFactoryCode();
    	   log.info("从redis获取" + factoryCodeRedis);
    	   if (!factoryCodeRedis.equals(factoryCode)) {
    		   log.warn("redis存储基地信息与用户选择信息不匹配：用户选择" + factoryCode + "   redis数据：" + factoryCodeRedis);
    	       return "基地信息不匹配,请重新登录";
    	   }
    	   log.info("用户：" + user + " 选择基地：" + factoryCode + "  登陆Token为：" + token);
    	   return "基地信息保存成功";
       }
       else
       {
           log.warn("Token: "+ token + " 从Redis获取用户信息失败,执行对象 currentUser is null");
           return "获取用户信息失败,请重新登录";
       }
    }
    	else
    	{
    		 log.warn("factoryCode不允许为空");
    		 return "factoryCode不允许为空";
    	}
    }
    
    /**
     *  从redis获取用户选择的基地
     * 
     * @param 无
     * @return 基地
     */
    
    public String selectRedisFactory(String token)
    {      
    	   
	       SysUser currentUser = redis.get(Constants.ACCESS_TOKEN + token, SysUser.class);
	       if (currentUser != null)
	       {  
	    	   SysFactory factoryRedis = redis.get(Constants.ACCESS_FACTORY + ":" + token + "_" + currentUser.getUserId(),SysFactory.class);
	    	   String factoryCodeRedis = factoryRedis.getFactoryCode();
	    	   log.info("从redis获取基地" + factoryCodeRedis);
	    	   if (factoryCodeRedis !=null) 
	    	   {
	    	   return factoryCodeRedis;
	    	   }
	    	   else
	    	   {
	    		   return "无用户基地数据";	  
	    	   }
        }
	       else
	       {
	    	   return "无法获取当前用户";	   
	       }
    }
    
    /**
     *  从redis获取用户id
     * 
     * @param 无
     * @return 用户ID
     */
    
    public Long selectRedisUserId()
    {      
           HttpServletRequest request = ServletUtils.getRequest() ;
           String token = request.getHeader("token");
	       SysUser currentUser = redis.get(Constants.ACCESS_TOKEN + token, SysUser.class);
	       if (currentUser != null)
	       {  
	    	   Long userID = currentUser.getUserId();
	    	   log.info("从redis获取用户id" + userID);
	    	   return userID;
        }
	       else
	       {
	    	   return null;	   
	       }
    }


    /**
     * 新增基地
     * 
     * @param sysFactory 基地
     * @return 结果
     */
    @Override
    public int insertSysFactory(SysFactory sysFactory)
    {
        return sysFactoryMapper.insertSysFactory(sysFactory);
    }

    /**
     * 修改基地
     * 
     * @param sysFactory 基地
     * @return 结果
     */
    @Override
    public int updateSysFactory(SysFactory sysFactory)
    {
        return sysFactoryMapper.updateSysFactory(sysFactory);
    }

    /**
     * 删除基地对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteSysFactoryByIds(String ids)
    {   
    	Long[] factoryIdsLongs = Convert.toLongArray(ids);
    	for (Long factoryIdsLong : factoryIdsLongs)
    	{ 
    	  int useLong = sysUserFactoryMapper.countUserFactoryByFactoryId(factoryIdsLong);
  	      int roleLong = sysRoleFactoryMapper.selectCountRoleFactoryByFactoryId(factoryIdsLong);
    	  if (sysUserFactoryMapper.countUserFactoryByFactoryId(factoryIdsLong) > 0 || sysRoleFactoryMapper.selectCountRoleFactoryByFactoryId(factoryIdsLong) > 0) 
    	  {   
    		  System.out.println( useLong + roleLong);
    		throw new BusinessException(String.format("%1$s已分配,不能删除", sysFactoryMapper.selectSysFactoryById(factoryIdsLong)));
    	  } 
    	}
    	  if (factoryIdsLongs.length>0) return sysFactoryMapper.deleteSysFactoryByIds(Convert.toStrArray(ids));
    	return 0;
    }

    /**
     * 删除基地信息
     * 
     * @param factoryId 基地ID
     * @return 结果
     */
    public int deleteSysFactoryById(Long factoryId)
    {   
    	if (sysUserFactoryMapper.countUserFactoryByFactoryId(factoryId) > 0 || sysRoleFactoryMapper.selectCountRoleFactoryByFactoryId(factoryId) > 0) 
    	{
    		throw new BusinessException(String.format("%1$s已分配,不能删除", sysFactoryMapper.selectSysFactoryById(factoryId)));
    	}
    	else 
    	{
        return sysFactoryMapper.deleteSysFactoryById(factoryId);
    	}
    }

}
